package com.roc.web.action.terminal;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.roc.bean.AreaBean;
import com.roc.bean.MerDetailForysBean;
import com.roc.bean.TermActForYsbBean;
import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Operators;
import com.roc.service.IExcelService;
import com.roc.service.ServiceException;
import com.roc.service.area.IAreaService;
import com.roc.service.operator.IPowerInfoService;
import com.roc.util.Constance;
import com.roc.util.Utils;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;
import com.roc.web.action.merinfo.FormalMerinfoSearchCondtion;
import com.roc.web.action.merinfo.MerDetailInfoForysbAction;
import com.roc.web.action.merinfo.MerDtInfoForysbSearchCondition;

@Controller
@SuppressWarnings("all")
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
@Namespace("/termianlActCount")
public class TermianlActCountForYsbAction extends PaginationBaseAction {
	private Logger logger=LogManager.getLogger(MerDetailInfoForysbAction.class);
	private TermianlActForYsbSearchCondition searchCondition;
	@Autowired
	IPageService pagenitionService;
	@Autowired
	IExcelService excelService;
	private InputStream excelFile;
	@Autowired
	private IPowerInfoService powerInfoService;
	private List<AreaBean> areaCodeList = new ArrayList<AreaBean>();
	@Autowired
	IAreaService areaService;

	@Action(value = "pageInit", results = {@Result(name =SUCCESS, location = "/pages/terminal/termianlCountForYsbList.jsp"),
			@Result(name = ERROR, location = "/error.jsp") })
	public String pageInit(){
		Operators op = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		try{
		if(op.getRoleType().equals(Role.OPERATORS_COMM.getCode())){
			Map<String, String> map=powerInfoService.queryRealIdByOpId(op.getSuperiorId(), op.getRoleType(), op.getId(), op.getOrgCode());
			String superRole= map.get("superRole");
			String opRealId =map.get("opRealId");
			Operators operator1 = powerInfoService.loadOperatorsById(new Long(opRealId));//分批终端序列号目的对象
				op.setSuperiorId(operator1.getSuperiorId());
				op.setRoleType(superRole);
				op.setId(Long.valueOf(opRealId));
		}
		if(!("sdsyb".equals(op.getAccountNo())
			||((op.getRoleType().equals(Role.AGENT.getCode())||op.getRoleType().equals(Role.O_MANAGER.getCode()))
					&&op.getSuperiorId().toString().equals("40001"))||op.getRoleType().equals(Role.SYSTEM.getCode()))) {
				addActionError("当前登录账号无权限访问!!!");
				return ERROR;
			}
		}catch (Exception e) {
			logger.error(e.getMessage(), e);
			addActionError(e.getMessage());
			return ERROR;
		}
		return SUCCESS;
	}
	
	@Action(value = "termianlCountForYsbList", results = {
			@Result(name = SUCCESS, location = "/pages/terminal/termianlCountForYsbList.jsp"),
			@Result(name = ERROR, location = "/error.jsp") })
	public String termianlCountForYsbList(){
		Operators op = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		try {
			 if(op.getRoleType().equals(Role.OPERATORS_COMM.getCode())){
				Map<String, String> map=powerInfoService.queryRealIdByOpId(op.getSuperiorId(), op.getRoleType(), op.getId(), op.getOrgCode());
				String superRole= map.get("superRole");
				String opRealId =map.get("opRealId");
				Operators operator1 = powerInfoService.loadOperatorsById(new Long(opRealId));//分批终端序列号目的对象
				op.setSuperiorId(operator1.getSuperiorId());
				op.setRoleType(superRole);
				op.setId(Long.valueOf(opRealId));
			}
			 if(!("sdsyb".equals(op.getAccountNo())
				||((op.getRoleType().equals(Role.AGENT.getCode())||op.getRoleType().equals(Role.O_MANAGER.getCode()))
					&&op.getSuperiorId().toString().equals("40001"))||op.getRoleType().equals(Role.SYSTEM.getCode()))) {
				addActionError("当前登录账号无权限访问!!!");
					return ERROR;
				}
			if (searchCondition == null) {
				searchCondition = (TermianlActForYsbSearchCondition) getSearchConditionFromSession();
				if (searchCondition == null) {
					searchCondition = new TermianlActForYsbSearchCondition();
				}
			}
			if(!(op.getRoleType().equals(Role.SYSTEM.getCode()) || "sdsyb".equals(op.getAccountNo()))){
				areaCodeList = areaService.queryAreaInfByOp(op);
				if(areaCodeList != null && areaCodeList.size() > 0){
					searchCondition.setAreaName(areaCodeList.get(0).getName());
				}else{
					addActionMessage("当前登录账号无所属大区！");
					return SUCCESS;
				}
			}
			int rows = pagenitionService.countSQL(searchCondition);
			if(rows > 0){
				searchRsList = pagenitionService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
				if(searchRsList.size() > 0 && searchRsList != null){
					List<TermActForYsbBean> termCountList = handleResultForObjectList(searchRsList);
					searchRsList.clear();
					searchRsList.addAll(termCountList);
				}
			}
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute("COUNT", rows);//当前条件统计总数
			getRequest().setAttribute(SEARCH_RS_LIST, searchRsList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			setSearchToConditionSession(searchCondition);
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
			return ERROR;
		}
		return SUCCESS;
	}
	
	public List<TermActForYsbBean> handleResultForObjectList(List<Object> objList) throws Exception{
		List<TermActForYsbBean> teList = new ArrayList<TermActForYsbBean>();
		Iterator<?> iterator=objList.iterator();
		while(iterator.hasNext()){
			Object[] obj = (Object[]) iterator.next();
			TermActForYsbBean termBean = new TermActForYsbBean();
			termBean.setAreaName(Constance.Null2EmptyTrim(obj[0])); //大区
			termBean.setOneagentName(Constance.Null2EmptyTrim(obj[1]));
			termBean.setOneagentNo(Constance.Null2EmptyTrim(obj[2]));
			termBean.setPosCount(Constance.Null2EmptyTrim(obj[3]));
			termBean.setPosType(Constance.Null2EmptyTrim(obj[4]));
			termBean.setYesday(Constance.Null2EmptyTrim(obj[5]));
			teList.add(termBean);
		}
		return teList;
	}
	
	@Action(value = "exportYsbTermActList", results = {
			@Result(name = "success", type = "stream", params = {
					"contentType", "application/vnd.ms-excel", "inputName",
					"excelFile", "contentDisposition",
					"attachment;filename=${excelName}.xls", "bufferSize",
					"1024*3" }),
			@Result(name = "error", location = "/pages/terminal/termianlCountForYsbList.jsp") })
	public String exportYsbTermActList(){
		logger.info("导出付临门云商宝终端激活数量信息");
			if(searchCondition==null){
				searchCondition=(TermianlActForYsbSearchCondition)getSearchConditionFromSession();
				if(searchCondition==null){
					searchCondition=new TermianlActForYsbSearchCondition();
				}
			}
			try {
				int rows=pagenitionService.countSQL(searchCondition);
				if(rows>0){
					searchRsList=pagenitionService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), rows);
				}
				List<TermActForYsbBean> dtList = handleResultForObjectList(searchRsList);
				SXSSFWorkbook work=excelService.exportYsbTermActList(dtList);
				ByteArrayOutputStream output = new ByteArrayOutputStream();
				work.write(output);
				byte[] ba = output.toByteArray();
				excelFile = new ByteArrayInputStream(ba);
				output.flush();
				output.close();
			} catch (Exception e) {
				e.printStackTrace();
				logger.error(e.getMessage(),e);
				addActionError(e.getMessage());
			}
			return SUCCESS;
		}		
	
	public String getExcelName() {
		String excelName="付临门云商宝终端激活数量统计"+Constance.formateDate();
			try {
				excelName = new String(excelName.getBytes(),"ISO8859-1");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				logger.info("生成excel名称失败了！");
			}
		return  excelName;
	}
	
	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);

	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_YSBTERM_ACTIV_LIST_QUERY, searchCondition);

	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		return (TermianlActForYsbSearchCondition)getSession().getAttribute(SEARCH_SESSION_YSBTERM_ACTIV_LIST_QUERY);
	}

	@Override
	protected String getInitPageSize() {
		return Constance.PAGE_MAX_SIZE + "";
	}

	public TermianlActForYsbSearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(TermianlActForYsbSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}

	public InputStream getExcelFile() {
		return excelFile;
	}

	public void setExcelFile(InputStream excelFile) {
		this.excelFile = excelFile;
	}

}
